﻿using WMLogistics.Model;
using WMLogistics_Dao;
using WMLogistics.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DapperExtensions;
using Logistics.Utility;

namespace WMLogistics.Service
{
    public class BidLoadService
    {
        private BidLoadDao dao = new BidLoadDao();
        private Bid_CloseDao closeDao = new Bid_CloseDao();
        private BidBaseService baseSevice = new BidBaseService();
        private BidWLPriceService priceSerivice = new BidWLPriceService();
        private ReportBidDao reportDao = new ReportBidDao();


        public PageData<wuliu_bid_load> GetBidLoadList(IPredicate predicate,  int pageIndex, int pageSize)
        {
            return dao.GetBidLoadList(predicate, pageIndex, pageSize);
        }
        public object GetPhoneLoadInfo(int flag, int load_id)
        {
            return dao.GetPhoneLoadInfo(flag, load_id);
        }


        public object GetWebLoadInfo(int loadid)
        {
            return dao.GetWebLoadInfo(loadid);
        }

        /// <summary>
        /// 获取电话列表
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public PageModel GetPhoneLoadList(IPredicate predicate, int pageIndex, int pageSize)
        {
            return dao.GetPhoneLoadList(predicate, pageIndex, pageSize);
        }

        public bool UpdateRemark(int id, string remark)
        {
            return dao.UpdateRemark(id, remark);
        }

        /// <summary>
        /// 关闭运单
        /// </summary>
        /// <param name="close"></param>
        /// <returns></returns>
        public bool ClsoeBid(wuliu_bid_close close)
        {
            var reportId = AddReport(close);
            var flag =  baseSevice.ScrapBid(close);


           var closeflag = dao.ClsoeBid((int)close.bid_id, close.load_no, 140, "10");

           return flag && closeflag && reportId > 0;


        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="close"></param>
        /// <returns></returns>
        private int AddReport(wuliu_bid_close close)
        {
            var reportId = 0;
            if (close.damage > 0)
            {
                wuliu_report_base report = new wuliu_report_base();
                var bidBase = baseSevice.GetBid((int)close.bid_id);
                var bidLoad = dao.GetBidLoad(close.load_no);
                var bidPrice = priceSerivice.GetPriceBidByWuliuId(bidBase.bid_no, (int)bidLoad.wuliu_id);
                report.report_start_time = (int)bidBase.start_bid_time;
                report.price = bidLoad.price;//未知
                report.report_end_time = (int)bidBase.end_bid_time;
                report.report_time = (int)DateTime.Now.Subtract(new System.DateTime(1970, 1, 1)).TotalSeconds;
                report.state = 1;
                if (bidPrice!=null)
                {
                    
                    //report.bill_price = (bidPrice.tax_price == null) ? 0 : bidPrice.tax_price;//
                    if(close.damage_flag=="10")
                    {
                        report.damage = -close.damage;
                    }
                    else
                    {
                        report.damage = close.damage;
                    }
                    //report.price = (bidPrice.price == null) ? 0 : bidPrice.price;//10 物流对企业
                    //report.tax = bidPrice.tax;
                    //report.tax_price = bidPrice.tax_price;
                }
              
                report.wuliu_id = bidLoad.wuliu_id;
                report.bid_id = bidBase.bid_id;
                report.company_id = bidBase.company_id;
                report.bid_no = bidBase.bid_no;
                report.order_num = bidBase.number;
                report.receipt_time = (int)bidBase.receipt_time;
                report.end_city_id = bidBase.end_city_id;
                report.wuliu_no = bidLoad.wuliu_no;
                report.pickup_time = (int)DateTime.Now.Subtract(new System.DateTime(1970, 1, 1)).TotalSeconds;
                report.bill_price = report.damage;
               
                report.Operator = close.Operator;
                reportId = reportDao.Add(report);
            }
            return reportId;
        }

        /// <summary>
        /// 第一次未取货重新选标选中操作
        /// </summary>
        /// <param name="close"></param>
        /// <param name="price_id"></param>
        /// <param name="load"></param>
        /// <returns></returns>
        public bool NotPickUp(wuliu_bid_close close, int price_id, wuliu_bid_wlcompany pricemod, wuliu_bid_load load)
        {
            var reportId = AddReport(close);
            var bz = priceSerivice.NotPickUp((int)close.bid_id);//更新原来选中的状态
            close.bid_state = 1;
            closeDao.Add(close);//保存拒单原因
            var pz = dao.NotPickUp(close.load_no);// 废弃原来的运单
            var choicebz = priceSerivice.ChoiceReBidPirce((int)close.bid_id, price_id, pricemod, load);//选择最新标单产生新的运单

            //dao.NotPickUp((int)close.bid_id, wuliu_id);

            return bz && pz && choicebz && reportId>0;
        }

        /// <summary>
        /// 重新未取货重新选标
        /// </summary>
        /// <param name="load"></param>
        /// <param name="price_id"></param>
        /// <param name="newLoad"></param>
        /// <returns></returns>
        public bool ReNotPickUp(wuliu_bid_load load, int price_id,wuliu_bid_wlcompany pricemod, wuliu_bid_load newLoad)
        {
            var bz = priceSerivice.NotPickUp((int)load.bid_id);//更新原来选中的状态  
            var pz = dao.NotPickUp(load.load_no);//废弃原来的运单
            var choicebz = priceSerivice.ChoiceReBidPirce((int)load.bid_id, price_id, pricemod, newLoad);//选择最新标单产生新的运单
            //var load_id = Add(newLoad);
            return bz && pz && choicebz;

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="log"></param>
        /// <returns></returns>
        public bool AddBidLoad(wuliu_bid_load_log log)
        {
            return dao.AddBidLoad(log);
        }

        /// <summary>
        /// 已取货public bool AddBidLoad(wuliu_bid_load_log log)
        /// </summary>
        /// <param name="loadno"></param>
        /// <returns></returns>
        public bool BillPick(string loadno,string opeartor)
        {
            var load = dao.GetBidLoad(loadno);
            wuliu_bid_base bid = new wuliu_bid_base();
            bid.bid_id = load.bid_id;
            bid.pickup_time = DateTimeToStamp(DateTime.Now);
            bid.state = 110;
            bid.wuliu_id = load.wuliu_id;
            bid.wuliu_name = load.wuliu_name;
            bid.wuliu_no = load.wuliu_no;
            try
            {
                wuliu_bid_load_log bidloadlog = new wuliu_bid_load_log();
                bidloadlog.bid_id = bid.bid_id;
                bidloadlog.bid_no = load.bid_no;
                bidloadlog.load_no = loadno;
                bidloadlog.wuliu_id = load.wuliu_id;
                bidloadlog.wuliu_name = load.wuliu_name;
                bidloadlog.wuliu_no = load.wuliu_no;
                bidloadlog.remark = "您已取货";
                bidloadlog.Operator = opeartor;
                bidloadlog.operator_time = DateTime.Now;
                dao.AddBidLoad(bidloadlog);
            }
            catch { }
            
            return dao.BidPick(loadno) && baseSevice.BidBaseUpdate(bid) >0;
        }
        // DateTime时间格式转换为Unix时间戳格式
        private int DateTimeToStamp(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        private int Add(Model.wuliu_bid_load newLoad)
        {
            return dao.Add(newLoad);
        }

        /// <summary>
        /// 回单确认
        /// 注：会往回单确认表和结算表里面存数据，并且根据运单表状态为已回单确认
        /// </summary>
        /// <param name="pickback"></param>
        /// <returns></returns>
        public bool Pickback(wuliu_bid_pickback pickback)
        {
            wuliu_report_base report = new wuliu_report_base();
            var bidBase = baseSevice.GetBid((int)pickback.bid_id);
            var bidLoad = dao.GetBidLoad(pickback.load_no);
            //var bidPrice = priceSerivice.GetPriceBidByWuliuId(bidBase.bid_no, (int)bidLoad.wuliu_id);
            if (bidBase == null)
                throw new Exception(string.Format("未找到对应的标单编号为({0})数据!", pickback.bid_no));
            if (bidLoad == null)
                throw new Exception(string.Format("未找到对应的运单编号为({0})数据!", pickback.bid_id));
            //if (bidPrice == null)
            //    throw new Exception(string.Format("未找到对应的物流编号为({0})数据!", bidLoad.wuliu_no));
            report.report_start_time = (int)bidBase.start_bid_time;
            report.kq_price = 1;//未知
            report.report_end_time = (int)bidBase.end_bid_time;
            report.report_time = DateTimeToStamp(DateTime.Now);
            report.state = 1;
            report.price = bidLoad.price;//
            report.tax = bidLoad.tax;
            report.tax_price = bidLoad.tax_price;
            report.wuliu_id = bidLoad.wuliu_id;
            report.bid_id = bidBase.bid_id;
            report.company_id = bidBase.company_id;
            report.company_name = bidLoad.company_name;
            report.company_no = bidLoad.company_no;
            report.load_no = bidLoad.load_no;
            report.wuliu_id = bidLoad.wuliu_id;
            report.wuliu_name = bidLoad.wuliu_name;
            report.wuliu_no = bidLoad.wuliu_no;
            report.bid_no = bidBase.bid_no;
            report.order_num = bidBase.number;
            report.report_time = (int)bidBase.receipt_time;
            report.end_city_id = bidBase.end_city_id;
            report.pickup_time = DateTimeToStamp(DateTime.Now);
            report.damage = pickback.damage;
            decimal billprie = 0;
            if (pickback.damage_flag=="1")//#赔偿方式（1 企业给物流 ， 10 物流给企业）
            {
                billprie = (decimal)(bidLoad.price + pickback.damage);
            }
            else
            {
                billprie = (decimal)(bidLoad.price - pickback.damage);
            }
            report.bill_price = billprie;//结算价
            report.Operator = pickback.Operator;
            var reportId = reportDao.Add(report);

            wuliu_bid_base bid = new wuliu_bid_base();
            bid.bid_id = pickback.bid_id;
            bid.state = 120;
            bid.pickup_time = DateTimeToStamp(DateTime.Now);
            bid.truetime = DateTimeToStamp(DateTime.Now);
            pickback.pickup_time = DateTime.Now;
            bool pickfla = dao.Pickback(pickback);
            bool editloadfla = dao.EditLoadState(pickback.load_no, 40, DateTime.Now);
            bool bidupdatefla = baseSevice.BidBaseUpdate(bid) > 0;

            try
            {
                wuliu_bid_load_log bidloadlog = new wuliu_bid_load_log();
                bidloadlog.bid_id = bid.bid_id;
                bidloadlog.bid_no = bidLoad.bid_no;
                bidloadlog.load_no = bidLoad.load_no;
                bidloadlog.wuliu_id = bidLoad.wuliu_id;
                bidloadlog.wuliu_name = bidLoad.wuliu_name;
                bidloadlog.wuliu_no = bidLoad.wuliu_no;
                bidloadlog.remark = "您的运单已回单确认";
                bidloadlog.Operator = pickback.Operator;
                bidloadlog.operator_time = DateTime.Now;
                dao.AddBidLoad(bidloadlog);
            }
            catch { }

            return pickfla && reportId > 0 && editloadfla && bidupdatefla;
        }

        public PageData<wuliu_bid_load> GetTranspotList(IPredicate pe, int page, int size)
        {
            return dao.GetTranspotList(pe, page, size);
        }

        public int GetTranspotCount(IPredicate pe)
        {
            return dao.GetTranspotCount(pe);
        }


        public wuliu_bid_load  GetBidLoadDeltial(int loadid)
        {
            return dao.GetBidLoadDeltial(loadid);
        }

        public wuliu_bid_load GetLoad(string load_no)
        {
            return dao.GetBidLoad(load_no);
        }

    }
}
